package org.openems;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.openems.meta.UserModelMeta;
import org.openems.model.UserModel;
import org.slim3.datastore.Datastore;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@Path("/user") 
public class UserResouce {
    @GET
    @Produces(MediaType.APPLICATION_XML)
    public UserEntity get() {
        User user = getUser();
        if (user != null) {
            UserModelMeta e = UserModelMeta.get();
            UserModel userModel = Datastore.query(e).filter(e.email.equal(user.getEmail())).asSingle();
            UserEntity ret = new UserEntity();
            if (userModel != null) {
               // ret.email = userModel.getEmail();
                ret.name = userModel.getName();
            }
            return ret;
        }
        else {
            UserEntity ret = new UserEntity();
            ret.name = "NOT LOGGED IN";
            return ret;
        }
    }

    private User getUser() {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        return user;
    }
    
    @POST
    @Produces("text/plain")
    @Consumes("application/xml")
    public String post(UserEntity entity) {
        String email = getUser().getEmail();
        UserModelMeta e = UserModelMeta.get();
        
//        try {
            UserModel userModel = Datastore.query(e).filter(e.email.equal(email)).asSingle();
            if (userModel == null) {
                userModel = new UserModel();
                userModel.setEmail(email);
                userModel.setName(entity.name);
                Datastore.put(userModel);
            }
//        }
//        catch (Exception ex) {
//            return ex.getMessage();
//        }
        return "OK";
    }
}
